package com.sgcc.fj.pmos.mobileapp.fragment;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.sgcc.fj.pmos.common.base.MvpBaseFragment;
import com.sgcc.fj.pmos.common.bean.ImageInfoBean;
import com.sgcc.fj.pmos.common.http.HttpInterConst;
import com.sgcc.fj.pmos.common.utils.GlideUtil;
import com.sgcc.fj.pmos.common.utils.SysUtil;
import com.sgcc.fj.pmos.common.utils.XXPermissionsUtil;
import com.sgcc.fj.pmos.common.utils.picture.PictureSelectUtil;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.fj.pmos.mobileapp.activity.AssociatedEnterpriseInfoActivity;
import com.sgcc.fj.pmos.mobileapp.bean.DataDifferentItemBean;
import com.sgcc.fj.pmos.mobileapp.bean.QueryLegalInfoBean;
import com.sgcc.fj.pmos.mobileapp.contract.LegalPersonInfoContract;
import com.sgcc.fj.pmos.mobileapp.presenter.LegalPersonInfoPresenter;
import com.sgcc.fj.pmos.mobileapp.utils.DataDifferent1Dialog;
import com.sgcc.fj.pmos.mobileapp.utils.DataDifferentDialog;
import com.sgcc.fj.pmos.mobileapp.utils.OnNextListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author ChaoAJ
 * @describe 关联企业信息--法人信息
 * @time 2022/10/18 11:45
 */
public class LegalPersonInfoFragment extends MvpBaseFragment<LegalPersonInfoPresenter> implements LegalPersonInfoContract.View, View.OnClickListener {

    //    证件类型（1身份证，2）护照，3港澳通行证，4台湾通行证，9其他）
    private String[] cardTypes = new String[]{"身份证", "护照", "港澳通行证", "台湾通行证", "其他"};


    private TextView tvCardType;
    private ImageView imgIdCard1;
    private ImageView imgIdCard2;
    private EditText etIDCardName;
    private EditText etIdCardNum;
    private EditText etIdCardPhoneNum;
    private TextView tvIdCardHide1;
    private ConstraintLayout clIdCardHide2;
    private TextView tvIdCardHide2;
    private TextView tvUnlockEdit;
    private LinearLayout llInfoLayout;


    private String cardType = "1";//证件类型
    private String idCardPath1 = "";//正面
    private String idCardPath2 = "";//背面


    //接口返回的法人信息
    private String legalReprName; //法人姓名
    private String doucumentNumber; //法人身份证号
    private String legalPhone; //法人手机号


    private OnNextListener onNextListener;
    private boolean isLock = true;


    public static LegalPersonInfoFragment newInstance() {
        LegalPersonInfoFragment fragment = new LegalPersonInfoFragment();
        return fragment;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_legal_person_info;
    }

    @Override
    protected LegalPersonInfoPresenter createPresenter() {
        return new LegalPersonInfoPresenter();
    }


    @Override
    protected void initViews() {
        super.initViews();
        llInfoLayout = mRootView.findViewById(R.id.llInfoLayout);
        tvUnlockEdit = mRootView.findViewById(R.id.tvUnlockEdit);

        tvCardType = mRootView.findViewById(R.id.tvCardType);
        imgIdCard1 = mRootView.findViewById(R.id.imgIdCard1);
        imgIdCard2 = mRootView.findViewById(R.id.imgIdCard2);

        etIDCardName = mRootView.findViewById(R.id.etIDCardName);
        etIdCardNum = mRootView.findViewById(R.id.etIdCardNum);
        etIdCardPhoneNum = mRootView.findViewById(R.id.etIdCardPhoneNum);


        tvIdCardHide1 = mRootView.findViewById(R.id.tvIdCardHide1);
        clIdCardHide2 = mRootView.findViewById(R.id.clIdCardHide2);
        tvIdCardHide2 = mRootView.findViewById(R.id.tvIdCardHide2);
        mPresenter.queryLegalInfo();
        unlockEdit();
    }

    @Override
    protected void initData() {
        super.initData();

        tvUnlockEdit.setOnClickListener(this);
        tvCardType.setOnClickListener(this);
        imgIdCard1.setOnClickListener(this);
        imgIdCard2.setOnClickListener(this);

    }


    private void setView() {
        String text1 = "";
        String text2 = "";
        int visibility = View.VISIBLE;
        switch (cardType) {
            case "1":
                text1 = "上传身份证人像面";
                text2 = "上传身份证国徽面";
                visibility = View.VISIBLE;
                break;
            case "2":
                text1 = "上传护照正面照";
                text2 = "上传护照反面照";
                visibility = View.VISIBLE;
                break;
            case "3":
                text1 = "上传港澳通行证正面照";
                text2 = "上传港澳通行证反面照";
                visibility = View.VISIBLE;
                break;
            case "4":
                text1 = "上传台湾通行证正面照";
                text2 = "上传台湾通行证反面照";
                visibility = View.VISIBLE;
                break;
            case "9":
                text1 = "上传证件正面照";
                text2 = "";
                visibility = View.GONE;
                break;
        }
        tvIdCardHide1.setText(text1);
        tvIdCardHide2.setText(text2);
        clIdCardHide2.setVisibility(visibility);
        imgIdCard1.setImageResource(R.mipmap.ic_id_card1);
        imgIdCard2.setImageResource(R.mipmap.ic_id_card2);
        idCardPath1 = "";
        idCardPath2 = "";
        etIDCardName.setText("");
        etIdCardNum.setText("");
        etIdCardPhoneNum.setText("");
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        KeyboardUtils.hideSoftInput(getActivity());
        if (id == R.id.tvUnlockEdit) {
            isLock = !isLock;
            unlockEdit();
        } else if (id == R.id.tvCardType) {
            new XPopup.Builder(getContext())
                    .asBottomList("请选择一项", cardTypes,
                            new OnSelectListener() {
                                @Override
                                public void onSelect(int position, String text) {
                                    if (position == 4) {
                                        cardType = "9";
                                    } else {
                                        cardType = position + 1 + "";
                                    }
                                    tvCardType.setText(text);
                                    legalReprName = "";
                                    doucumentNumber = "";
                                    legalPhone = "";
                                    setView();
                                }
                            }).show();
        } else if (id == R.id.imgIdCard1) {
            XXPermissionsUtil.camera(getActivity(), new XXPermissionsUtil.PermissionCallback() {
                @Override
                public void Call() {
                    PictureSelectUtil.select(LegalPersonInfoFragment.this, 0x22, true, null);
                }
            });
        } else if (id == R.id.imgIdCard2) {
            XXPermissionsUtil.camera(getActivity(), new XXPermissionsUtil.PermissionCallback() {
                @Override
                public void Call() {
                    PictureSelectUtil.select(LegalPersonInfoFragment.this, 0x23, true, null);
                }
            });
        }
//        switch (id) {
//            case R.id.tvUnlockEdit:
//                isLock = !isLock;
//                unlockEdit();
//                break;
//            case R.id.tvCardType:
//                new XPopup.Builder(getContext())
//                        .asBottomList("请选择一项", cardTypes,
//                                new OnSelectListener() {
//                                    @Override
//                                    public void onSelect(int position, String text) {
//                                        if (position == 4) {
//                                            cardType = "9";
//                                        } else {
//                                            cardType = position + 1 + "";
//                                        }
//                                        tvCardType.setText(text);
//                                        legalReprName = "";
//                                        doucumentNumber = "";
//                                        legalPhone = "";
//                                        setView();
//                                    }
//                                }).show();
//
//
//                break;
//            case R.id.imgIdCard1:
//                XXPermissionsUtil.camera(getActivity(), new XXPermissionsUtil.PermissionCallback() {
//                    @Override
//                    public void Call() {
//                        PictureSelectUtil.select(LegalPersonInfoFragment.this, 0x22, true, null);
//                    }
//                });
//                break;
//            case R.id.imgIdCard2:
//
//                XXPermissionsUtil.camera(getActivity(), new XXPermissionsUtil.PermissionCallback() {
//                    @Override
//                    public void Call() {
//                        PictureSelectUtil.select(LegalPersonInfoFragment.this, 0x23, true, null);
//                    }
//                });
//                break;
//
//
//        }

    }


    //更改锁定状态
    private void unlockEdit() {
        tvUnlockEdit.setText(isLock ? "解锁编辑" : "锁定");
        //姓名
        etIDCardName.setSelected(!isLock);
        etIDCardName.setEnabled(!isLock);

        //名称
        etIdCardNum.setSelected(!isLock);
        etIdCardNum.setEnabled(!isLock);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            ArrayList<LocalMedia> localMediaList = PictureSelector.obtainSelectorList(data);
            if (null != localMediaList && localMediaList.size() > 0) {
                if (requestCode == 0x22) {
                    idCardPath1 = PictureSelectUtil.getPath(localMediaList.get(0));
                    GlideUtil.loadImg(idCardPath1, imgIdCard1);
                    mPresenter.uploadFile(idCardPath1, 0);
                } else if (requestCode == 0x23) {
                    idCardPath2 = PictureSelectUtil.getPath(localMediaList.get(0));
                    GlideUtil.loadImg(idCardPath2, imgIdCard2);
                    mPresenter.uploadFile(idCardPath2, 1);
                }
            }
        }
    }


    @Override
    public void uploadFileSuccess(ImageInfoBean.Info info) {
        if (null != info) {
            legalReprName = info.getLegalReprName().trim();
            doucumentNumber = info.getDoucumentNumber().trim();
            legalPhone = "";
            setText();
        }
    }


    @Override
    public void queryLegalInfoSuccess(QueryLegalInfoBean.LegalInfo legalInfo) {
        if (null != legalInfo) {
            legalReprName = legalInfo.getLegalReprName().trim();
            doucumentNumber = legalInfo.getDoucumentNumber().trim();
            legalPhone = legalInfo.getLegalPhone();
            cardType = legalInfo.getDoucumentType();
            setView();
            String text = "";
            if (cardType.equals("9")) {
                text = "其他";
            } else {
                text = cardTypes[Integer.parseInt(cardType) - 1];
            }
            tvCardType.setText(text);

            List<QueryLegalInfoBean.LegalInfo.MmMembersAffixRegsDTO> mmMembersAffixRegs = legalInfo.getMmMembersAffixRegs();
            if (null != mmMembersAffixRegs && mmMembersAffixRegs.size() > 0) {
                for (QueryLegalInfoBean.LegalInfo.MmMembersAffixRegsDTO mmMembersAffixReg : mmMembersAffixRegs) {
                    if (mmMembersAffixReg.getAffixType().equals("202")) {
                        idCardPath1 = HttpInterConst.BASEURL_IMG + mmMembersAffixReg.getFileId();
                        GlideUtil.loadImg(idCardPath1, imgIdCard1);
                    }
                    if (mmMembersAffixReg.getAffixType().equals("202a")) {
                        idCardPath2 = HttpInterConst.BASEURL_IMG + mmMembersAffixReg.getFileId();
                        GlideUtil.loadImg(idCardPath2, imgIdCard2);
                    }
                }

            }
            setText();
        }
    }

    @Override
    public void saveDataSuccess(String text) {
        if (null != onNextListener)
            onNextListener.onNext(true);
    }

    @Override
    public void onFailed(int code) {
        if (code == 0) {
            ToastUtils.showShort("文件上传失败");
        }
        if (code == 1) {
            llInfoLayout.setVisibility(View.VISIBLE);
            etIDCardName.setText("");
            etIdCardNum.setText("");
        }

    }

    private void setText() {

        llInfoLayout.setVisibility(View.VISIBLE);

        if (!TextUtils.isEmpty(legalReprName))
            etIDCardName.setText(legalReprName);
        if (!TextUtils.isEmpty(doucumentNumber))
            etIdCardNum.setText(doucumentNumber);
        if (!TextUtils.isEmpty(legalPhone))
            etIdCardPhoneNum.setText(legalPhone);
    }


    public void next(OnNextListener onNextListener) {
        this.onNextListener = onNextListener;

        if (TextUtils.isEmpty(idCardPath1)) {
            ToastUtils.showShort("请上传证件正面照");
            onNextListener.onNext(false);
            return;
        }
        if (!cardType.equals("9") && TextUtils.isEmpty(idCardPath2)) {
            ToastUtils.showShort("请上传证件反面照");
            onNextListener.onNext(false);
            return;
        }


        String name = etIDCardName.getText().toString().trim();//法人姓名
        if (TextUtils.isEmpty(name)) {
            ToastUtils.showShort("请输入姓名");
            onNextListener.onNext(false);
            return;
        }
        if (!RegexUtils.isZh(name)) {
            ToastUtils.showShort("姓名必须为汉字");
            onNextListener.onNext(false);
            return;
        }


        String cordId = etIdCardNum.getText().toString().trim();//法人证件号码
        if (TextUtils.isEmpty(cordId)) {
            ToastUtils.showShort("请输入证件号码");
            onNextListener.onNext(false);
            return;
        }
        // 1身份证，2护照，3港澳通行证，4台湾通行证，9其他）
        if (cardType.equals("1")) {//1身份证
            if (!RegexUtils.isIDCard18Exact(cordId)) {
                ToastUtils.showShort("身份证号码格式有误");
                onNextListener.onNext(false);
                return;
            }
        }
        if (cardType.equals("2")) {//2护照
            if (!SysUtil.isPassPortCard(cordId)) {
                ToastUtils.showShort("护照号码格式有误");
                onNextListener.onNext(false);
                return;
            }
        }
        if (cardType.equals("3")) {//3港澳通行证
            if (!SysUtil.isHMCard(cordId)) {
                ToastUtils.showShort("港澳通行证号码格式有误");
                onNextListener.onNext(false);
                return;
            }
        }
        if (cardType.equals("4")) {//4台湾通行证
            if (!SysUtil.isTWCard(cordId)) {
                ToastUtils.showShort("台湾通行证号码格式有误");
                onNextListener.onNext(false);
                return;
            }
        }

        String phoneNum = etIdCardPhoneNum.getText().toString().trim();//法人手机号
        if (TextUtils.isEmpty(phoneNum)) {
            ToastUtils.showShort("请输入法定代表人手机号");
            onNextListener.onNext(false);
            return;
        }
        if (!RegexUtils.isMobileExact(phoneNum)) {
            ToastUtils.showShort("法定代表人手机号格式有误");
            onNextListener.onNext(false);
            return;
        }

        List<DataDifferentItemBean> dataDifferentItemBeanList = new ArrayList<>();

        String legalReprName = ((AssociatedEnterpriseInfoActivity) getActivity()).getLegalReprName().trim();

        if (!legalReprName.equals(name)) {
            dataDifferentItemBeanList.add(new
                    DataDifferentItemBean("姓名", name, legalReprName));

            onNextListener.onNext(false);
            new XPopup.Builder(getContext())
                    .isDestroyOnDismiss(true)
                    .isViewMode(true)
                    .asCustom(new DataDifferent1Dialog(getContext(), dataDifferentItemBeanList))
                    .show();
            return;
        }


        //判断输入的和识别的是否一致
        if (!TextUtils.isEmpty(this.legalReprName))
            if (!this.legalReprName.equals(name)) {
                dataDifferentItemBeanList.add(new
                        DataDifferentItemBean("姓名", name, this.legalReprName));
            }
        if (!TextUtils.isEmpty(doucumentNumber))
            if (!doucumentNumber.equals(cordId)) {
                dataDifferentItemBeanList.add(new
                        DataDifferentItemBean("证件号码", cordId, doucumentNumber));
            }
        if (!TextUtils.isEmpty(legalPhone))
            if (!legalPhone.equals(phoneNum)) {
                dataDifferentItemBeanList.add(new
                        DataDifferentItemBean("法定代表人手机号", phoneNum, legalPhone));
            }

        if (dataDifferentItemBeanList.size() > 0) {
            new XPopup.Builder(getContext())
                    .isDestroyOnDismiss(true)
                    .isViewMode(true)
                    .asCustom(new DataDifferentDialog(getContext(), "您所填写的法定代表人信息与证件识别的信息不一致，请检查您所填信息是否准确！", dataDifferentItemBeanList
                            , new DataDifferentDialog.OnConfirmClickListener() {
                        @Override
                        public void onConfirm() {
                            save(name, cordId, phoneNum);
                        }
                    }))
                    .show();
        } else {
            save(name, cordId, phoneNum);
        }


    }

    private void save(String name, String idCord, String phoneNum) {
//        "doucumentType": "1", //证件类型（1身份证，2）护照，3港澳通行证，4台湾通行证，9其他）
//                "legalReprName": "张三", //姓名
//                "doucumentNumber": "140107199911111234", //证件号码
//                "legalPhone": "15012344321", //法定代表人手机号
//                "companyId": "123456",
//                "membersId": "123456" //售电公司ID(商品详情标题-店铺ID)
        Map<String, Object> params = new HashMap<>();
        params.put("doucumentType", cardType);
        params.put("legalReprName", name);
        params.put("doucumentNumber", idCord);
        params.put("legalPhone", phoneNum);

        mPresenter.saveData(params);

    }


}